﻿// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.

namespace Microsoft.Data.Entity.Design.Model.Mapping
{
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Globalization;
    using System.Xml.Linq;
    using Microsoft.Data.Entity.Design.Model.Entity;

    internal class EndProperty : EFElement
    {
        internal static readonly string ElementName = "EndProperty";
        internal static readonly string AttributeName = "Name";

        private readonly List<ScalarProperty> _properties = new List<ScalarProperty>();
        private SingleItemBinding<AssociationSetEnd> _name;

        internal EndProperty(EFElement parent, XElement element)
            : base(parent, element)
        {
        }

        /// <summary>
        ///     This will return this a type safe reference to this type's parent
        /// </summary>
        internal AssociationSetMapping AssociationSetMapping
        {
            get
            {
                var parent = Parent as AssociationSetMapping;
                return parent;
            }
        }

        /// <summary>
        ///     A bindable reference to the AssociationSetEnd for this end of the association set
        /// </summary>
        internal SingleItemBinding<AssociationSetEnd> Name
        {
            get
            {
                if (_name == null)
                {
                    _name = new SingleItemBinding<AssociationSetEnd>(
                        this,
                        AttributeName,
                        AssociationSetEndNameNormalizer.NameNormalizer);
                }
                return _name;
            }
        }

        internal void AddScalarProperty(ScalarProperty sp)
        {
            _properties.Add(sp);
        }

        internal IList<ScalarProperty> ScalarProperties()
        {
            return _properties.AsReadOnly();
        }

        // we unfortunately get a warning from the compiler when we use the "base" keyword in "iterator" types generated by using the
        // "yield return" keyword.  By adding this method, I was able to get around this.  Unfortunately, I wasn't able to figure out
        // a way to implement this once and have derived classes share the implementation (since the "base" keyword is resolved at 
        // compile-time and not at runtime.
        private IEnumerable<EFObject> BaseChildren
        {
            get { return base.Children; }
        }

        internal override IEnumerable<EFObject> Children
        {
            get
            {
                foreach (var efobj in BaseChildren)
                {
                    yield return efobj;
                }

                foreach (var child in ScalarProperties())
                {
                    yield return child;
                }

                yield return Name;
            }
        }

        protected override void OnChildDeleted(EFContainer efContainer)
        {
            var child1 = efContainer as ScalarProperty;
            if (child1 != null)
            {
                _properties.Remove(child1);
                return;
            }

            base.OnChildDeleted(efContainer);
        }

#if DEBUG
        internal override ICollection<string> MyAttributeNames()
        {
            var s = base.MyAttributeNames();
            s.Add(AttributeName);
            return s;
        }
#endif

#if DEBUG
        internal override ICollection<string> MyChildElementNames()
        {
            var s = base.MyChildElementNames();
            s.Add(ScalarProperty.ElementName);
            return s;
        }
#endif

        protected override void PreParse()
        {
            Debug.Assert(State != EFElementState.Parsed, "this object should not already be in the parsed state");

            ClearEFObject(_name);
            _name = null;
            ClearEFObjectCollection(_properties);

            base.PreParse();
        }

        private string DisplayNameInternal(bool localize)
        {
            string resource;
            if (localize)
            {
                resource = Resources.MappingModel_EndPropertyDisplayName;
            }
            else
            {
                resource = "{0} (EndProperty)";
            }

            return string.Format(
                CultureInfo.CurrentCulture,
                resource,
                Name.RefName);
        }

        internal override string DisplayName
        {
            get { return DisplayNameInternal(true); }
        }

        internal override string NonLocalizedDisplayName
        {
            get { return DisplayNameInternal(false); }
        }

        internal override bool ParseSingleElement(ICollection<XName> unprocessedElements, XElement elem)
        {
            if (elem.Name.LocalName == ScalarProperty.ElementName)
            {
                var sp = new ScalarProperty(this, elem);
                _properties.Add(sp);
                sp.Parse(unprocessedElements);
            }
            else
            {
                return base.ParseSingleElement(unprocessedElements, elem);
            }
            return true;
        }

        protected override void DoResolve(EFArtifactSet artifactSet)
        {
            Name.Rebind();
            if (Name.Status == BindingStatus.Known)
            {
                State = EFElementState.Resolved;
            }
        }

        internal override void GetXLinqInsertPosition(EFElement child, out XNode insertAt, out bool insertBefore)
        {
            if (child is ScalarProperty)
            {
                insertAt = FirstChildXElementOrNull();
                insertBefore = true;
            }
            else
            {
                base.GetXLinqInsertPosition(child, out insertAt, out insertBefore);
            }
        }
    }
}
